package com.tianyao.compose.baseuse.viewmodel

import androidx.compose.runtime.mutableStateListOf
import java.util.UUID

/**
 * 带稳定键的列表，适用于需要元素标识稳定的场景（如 Compose 列表渲染）
 * @param T 列表元素类型
 * @param initialList 初始元素列表（默认为空）
 * @param keyGenerator 元素键生成策略（默认使用 UUID）
 */
class StableKeyList<T> @JvmOverloads constructor(
    initialList: List<T> = emptyList(),
    private val keyGenerator: (T) -> Any = { _ -> UUID.randomUUID() }
) {
    private val items = mutableStateListOf<ItemWrapper<T>>()

    // 公开属性
    val values: List<T> get() = items.map { it.value }
    val size: Int get() = items.size

    init {
        internalAddAll(initialList)
    }

    /*-------------------------------- 核心操作 --------------------------------*/

    fun add(value: T) = internalAddAll(listOf(value))

    fun addAll(values: List<T>) = internalAddAll(values)

    fun remove(value: T) = items.removeAll { it.value == value }

    fun removeByKey(key: Any) = items.removeAll { it.key == key }

    fun clear() = items.clear()

    /*-------------------------------- 查询操作 --------------------------------*/

    fun getKey(index: Int): Any? = if (index in 0 until size) {
        items[index].key
    } else {
        null
    }

    fun getValue(index: Int): T? = if (index in 0 until size) {
        items[index].value
    } else {
        null
    }

    fun getItem(index: Int): ItemWrapper<T>? = if (index in 0 until size) {
        items[index]
    } else {
        null
    }

    fun contains(value: T): Boolean = items.any { it.value == value }

    fun containsKey(key: Any): Boolean = items.any { it.key == key }

    fun getValueByKey(key: Any): T? = items.firstOrNull { it.key == key }?.value

    fun getKeyByValue(value: T): Any? = items.firstOrNull { it.value == value }?.key

    /*-------------------------------- 更新操作 --------------------------------*/

    fun updateByKey(key: Any, newValue: T): Boolean {
        val index = items.indexOfFirst { it.key == key }
        return if (index != -1) {
            items[index] = items[index].copy(value = newValue)
            true
        } else {
            false
        }
    }


    // 新增通过值更新的方法
    fun updateValue(oldValue: T, newValue: T): Boolean {
        val key = getKeyByValue(oldValue)
        return key?.let { updateByKey(it, newValue) } ?: false
    }

    /*------------------------------- Compose 支持 -------------------------------*/

    fun getItemsForCompose(): List<ItemWrapper<T>> = items

    /*------------------------------- 内部实现细节 -------------------------------*/

    private fun internalAddAll(values: List<T>) {
        items.addAll(values.map { ItemWrapper(keyGenerator(it), it) })
    }

    data class ItemWrapper<T>(
        val key: Any, // 支持任意类型键
        val value: T
    )
}

